package com.frejoys.aop;

import com.frejoys.common.aop.Authority;
import com.frejoys.common.enums.ESite;
import com.frejoys.common.error.HttpStatus;
import com.frejoys.common.exception.GeneralException;
import com.frejoys.common.util.RequestUtil;
import com.frejoys.service.AuthRuleService;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
@Aspect
public class RouteRuleAop {

    private final AuthRuleService authRuleService;

    // private final UserService userService;

    @Pointcut("@within(com.frejoys.common.aop.Authorization) || @annotation(com.frejoys.common.aop.Authorization)")
    public void atestAop() {}

    @Before("atestAop()")
    public void before(JoinPoint joinPoint) {

        // 权限控制
        if (RequestUtil.authority() == Authority.Private) {
            if (RequestUtil.site() == ESite.store.getValue()) {
                // 检查用户是否是商家
                // User user = userService.getInfo(RequestUtil.userId());
                // if (!CommonUtil.bitExistOffset(user.getRole(), EUserRole.store.getValue())) {
                //     throw new GeneralException(HttpStatus.sotreRoleNoExist);
                // }
            } else if (RequestUtil.site() == ESite.admin.getValue()) {
                // 检查后台用户权限
                if (!authRuleService.authCheck(RequestUtil.userId(), RequestUtil.route())) {
                    throw new GeneralException(HttpStatus.routeRuleNone);
                }
            }
        }
    }

}
